package com.zjk.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjk.Result;
import com.zjk.category.CategoryEntity;
import com.zjk.dto.SearchSpuDTO;
import com.zjk.dto.SpuDTO;
import com.zjk.mapper.*;
import com.zjk.pojo.Brand;
import com.zjk.pojo.SpuImagesEntity;
import com.zjk.pojo.SpuInfoDescEntity;
import com.zjk.pojo.SpuInfoEntity;
import com.zjk.search.SearchItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: gfk
 * @create: 2022/10/21
 * @Description:
 * @FileName: SpuService
 * @History:
 * @自定义内容：
 */
@Service
public class SpuService {
    @Autowired
    SpuInfoMapper spuInfoMapper;
     @Autowired
    SpuInfoDescMapper spuInfoDescMapper;
     @Autowired
    SpuImagesMapper spuImagesMapper;

    @Autowired
    BrandMapper brandMapper;
    @Autowired
    CategoryMapper categoryMapper;

    /**
     *
     * @param pageNo
     * @param pageSize
     * @param searchSpuDTO
     * @return
     */
    public Page<SpuInfoEntity> spuList(Integer pageNo, Integer pageSize, SearchSpuDTO searchSpuDTO) {
        Page<SpuInfoEntity> page = new Page<>(pageNo,pageSize);

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String keyword = searchSpuDTO.getKeyword();
        if (StringUtils.isEmpty(searchSpuDTO.getKeyword())){
            LambdaQueryWrapper<SpuInfoEntity> like = queryWrapper.lambda().like(SpuInfoEntity::getSpuName, keyword)
                    .or().like(SpuInfoEntity::getSpuDescription, keyword);
        }

        Long categoryId = searchSpuDTO.getCategoryId();//level 3
        if (categoryId!=null && categoryId!=0){
            queryWrapper.lambda().eq(SpuInfoEntity::getCatalogId,categoryId);
        }

        Long brandId = searchSpuDTO.getBrandId();
        if (brandId!=null && brandId!=0){
            queryWrapper.lambda().eq(SpuInfoEntity::getBrandId,brandId);
        }

        Integer status = searchSpuDTO.getPublishStatus();
        if (status!=null && status!=0){
            queryWrapper.lambda().eq(SpuInfoEntity::getPublishStatus,status);
        }

        Date startTime = searchSpuDTO.getStartTime();
        if (startTime!=null){
            queryWrapper.lambda().gt(SpuInfoEntity::getCreateTime,startTime);
        }

        Date endTime = searchSpuDTO.getEndTime();
        if (endTime!=null){
            queryWrapper.lambda().gt(SpuInfoEntity::getUpdateTime,endTime);
        }

        Page<SpuInfoEntity> spuInfoEntityPage = spuInfoMapper.selectPage(page, queryWrapper);
        List<SpuInfoEntity> collect = spuInfoEntityPage.getRecords().stream().map(
                (spuInfoEntity) -> {
                    Brand brandEntity = brandMapper.selectById(spuInfoEntity.getBrandId());
                    spuInfoEntity.setBrandName(brandEntity.getName());
                    CategoryEntity categoryEntity = categoryMapper.selectById(spuInfoEntity.getCatalogId());
                    spuInfoEntity.setCatalogName(categoryEntity.getName());

                    return spuInfoEntity;
                }
        ).collect(Collectors.toList());
        spuInfoEntityPage.setRecords(collect);
        return spuInfoEntityPage;
    }

    /**
     * 根据spuId 查询描述信息
     * @param spuId
     * @return
     */
    public SpuInfoDescEntity selectSpuInfoDescBySpuId(Long spuId) {
        SpuInfoDescEntity spuInfoDescEntity = spuInfoDescMapper.selectById(spuId);

        return spuInfoDescEntity;
    }

    /**
     * 根据spuId 查询描述信息
     * @param spuId
     * @return
     */
    public List<SpuImagesEntity> selectSpuImagesDescBySpuId(Long spuId) {
        return null;
    }
    //事务 ACID  Aotimic 原子性   C 一致性  I 隔离性 D 持久性
    //undo log 回滚日志
    // Transactional 默认 抛出RuntimeException的时候回滚，如果想要自定义异常
    @Transactional(/*rollbackForClassName={"java.lang.Exception"}
            ,noRollbackForClassName = {"java.io.FileNotFoundException"}*/)
    public Result save(SpuDTO spuDTO) {

        if(spuDTO.getId()==null){//
            //保存第一张表
            SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
            BeanUtils.copyProperties(spuDTO,spuInfoEntity);
            spuInfoEntity.setCreateTime(new Date());
            spuInfoEntity.setUpdateTime(new Date());
            //spuInfoEntity.getId() 是 null
            spuInfoMapper.insert(spuInfoEntity);
            //spuInfoEntity.getId() 不是 null

            Long spuId = spuInfoEntity.getId();
            //保存第二张表
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setSpuId(spuId);//不是为null，主键关联 1：1
            spuInfoDescEntity.setDecript(spuDTO.getDecript());
            spuInfoDescMapper.insert(spuInfoDescEntity);

            if(spuDTO.getImagesList()!=null){
                spuDTO.getImagesList().stream().forEach((imagesUrl)->{
                    SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                    spuImagesEntity.setSpuId(spuId);//不是为null 关联关键
                    spuImagesEntity.setImgUrl(imagesUrl);
                    spuImagesMapper.insert(spuImagesEntity);
                });
            }
        }

        return new Result(true,1,"创建成功");
    }

    @Transactional
    public Result deleteBySpuId(Long spuId) {

        UpdateWrapper<SpuImagesEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(SpuImagesEntity::getSpuId,spuId);
        spuImagesMapper.delete(updateWrapper);

        UpdateWrapper<SpuInfoDescEntity> updateWrapper1 = new UpdateWrapper<>();
        updateWrapper1.lambda().eq(SpuInfoDescEntity::getSpuId,spuId);
        spuInfoDescMapper.delete(updateWrapper1);

        spuInfoMapper.deleteById(spuId);

        return new Result(true,1,"删除成功");
    }

    public List<SearchItem> findSearchItemList(Map searchMap) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        String  syncTime = (String) searchMap.get("lastSyncTime");

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(syncTime)){//时间步为空 增量查询
            queryWrapper.lambda().gt(SpuInfoEntity::getUpdateTime,syncTime);
        }else {
//时间为空 全量查询
        }
        List<SpuInfoEntity> entities = spuInfoMapper.selectList(queryWrapper);
        List<SearchItem> collect = entities.stream().map((spuInfoEntity) -> {
            SearchItem searchItem = new SearchItem();
            searchItem.setSpuId(spuInfoEntity.getId());
            searchItem.setTitle(spuInfoEntity.getSpuName() + spuInfoEntity.getSpuDescription());
            searchItem.setPrice(spuInfoEntity.getPrice().doubleValue());
            CategoryEntity entity = categoryMapper.selectById(spuInfoEntity.getCatalogId());
            searchItem.setCategory(entity.getName());
            Brand brand = brandMapper.selectById(spuInfoEntity.getBrandId());
            searchItem.setBrand(brand.getName());
            QueryWrapper<SpuImagesEntity> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(SpuImagesEntity::getSpuId, spuInfoEntity.getId());
            List<SpuImagesEntity> list = spuImagesMapper.selectList(wrapper);
            if (list.size() > 0) {
                if (list.get(0).getImgUrl() != null) {
                    searchItem.setMainPic(list.get(0).getImgUrl());
                }

            }
            searchItem.setUpdatetime(simpleDateFormat.format(spuInfoEntity.getUpdateTime()));
            return searchItem;
        }).collect(Collectors.toList());

        return collect;

    }
}
